package com.amigo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.amigo.helper.Constants;
import com.amigo.helper.JsonFileUtility;
import com.amigo.helper.ServiceHandler;
import com.amigo.views.SwipeRefreshHintLayout;
import com.amigo.views.adapter.PendingFriendRequestsList;

public class Notifications extends Activity {

	private SwipeRefreshLayout swipeView;
	ListView list;
	PendingFriendRequestsList adapter;
	private String url = Constants.base_url + "pendingRequests";
	private String url_addfriend = Constants.base_url
			+ "respondToFriendRequest";
	private TextView empty_view;
	// private Boolean Success;
	private String ID_by;
	private ArrayList<HashMap<String, String>> AmigosList;
	private ProgressBar loader;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_notifications);

		loader = (ProgressBar) findViewById(R.id.progressBar1);
		swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);

		SwipeRefreshHintLayout mSwipeRefreshHintLayout = (SwipeRefreshHintLayout) findViewById(R.id.swipe_hint);
		mSwipeRefreshHintLayout.setSwipeLayoutTarget(swipeView);
		swipeView.setColorSchemeColors(
				getResources().getColor(R.color.theme_secondary),
				getResources().getColor(R.color.white), getResources()
						.getColor(R.color.theme_secondary), getResources()
						.getColor(R.color.theme_background));
		swipeView
				.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

					@Override
					public void onRefresh() {

						new FetchAmigosTask().execute();
					}
				});

		AmigosList = new ArrayList<HashMap<String, String>>();
		empty_view = (TextView) findViewById(R.id.empty_view);
		empty_view.setVisibility(View.GONE);

		new FetchAmigosTask().execute();

		list = (ListView) findViewById(R.id.list_amigos);

		// Getting adapter by passing xml data ArrayList
		adapter = new PendingFriendRequestsList(this, AmigosList);
		list.setAdapter(adapter);
		list.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView absListView, int i) {

			}

			@Override
			public void onScroll(AbsListView absListView, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if (visibleItemCount > 0) {
					if (firstVisibleItem == 0) {

						if (list.getChildAt(0).getTop() == 0)
							swipeView.setEnabled(true);

						else
							swipeView.setEnabled(false);

					} else
						swipeView.setEnabled(false);
				}
			}
		});

		list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {

				HashMap<String, String> item = new HashMap<String, String>();

				item = AmigosList.get(position);

				Intent i = new Intent(Notifications.this, Profile.class);
				i.putExtra("user_from_pendingrequets", item.get("user_object"));
				startActivity(i);
				finish();

			}
		});

	}

	private class FetchAmigosTask extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			AmigosList.clear();
			empty_view.setVisibility(View.INVISIBLE);
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... args) {
			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("token", JsonFileUtility
					.ReadJsonData(Constants.TAG_UserGUID)));

			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST,
					params);

			Log.d("Response: ", "> " + jsonStr);

			if (jsonStr != null) {
				String dp = "init";
				try {
					JSONArray amigos = new JSONArray(jsonStr);
					for (int i = 0; i < amigos.length(); i++) {
						JSONObject amigo = amigos.getJSONObject(i);
						String name = amigo.getString("name");
						String location = amigo.getString("location");
						String id = amigo.getString("id");
						if (amigo.opt("profile_images") instanceof Boolean) {
							Log.d("STATUS", "no-dp");
							dp = "init";
						} else {
							JSONArray images = amigo
									.getJSONArray("profile_images");
							JSONObject first_image = images.getJSONObject(0);
							dp = first_image.getString("image_url");
						}
						HashMap<String, String> map = new HashMap<String, String>();

						map.put("user_name", name);
						map.put("user_location", location);
						map.put("image_url", dp);
						map.put("id", id);
						map.put("user_object", amigo.toString());

						AmigosList.add(map);

					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			loader.setVisibility(View.GONE);
			super.onPostExecute(result);
			if (swipeView.isRefreshing()) {
				swipeView.setRefreshing(false);
			}
			if (AmigosList.size() > 0) {
				adapter.notifyDataSetChanged();
				list.setAdapter(adapter);
			} else if (AmigosList.size() == 0) {
				adapter.notifyDataSetChanged();
				list.setAdapter(adapter);
				empty_view.setVisibility(View.VISIBLE);
			}

		}
	}

	public void prev(View v) {
		startActivity(new Intent(this, Dashboard.class));
		finish();
	}

	public void acceptreq(View v) {
		ID_by = v.getTag().toString();
		new AcceptRequestTask().execute();

	}

	public void rejectreq(View v) {

		ID_by = v.getTag().toString();
		new RejectRequesttask().execute();
	}

	public void maybelaterreq(View v) {

		ID_by = v.getTag(R.string.tag_id).toString();
		Log.d("position" , v.getTag(R.string.tag_position).toString());
		int position = Integer.parseInt(v.getTag(R.string.tag_position).toString());
		AmigosList.remove(position);
		adapter.notifyDataSetChanged();
		if(AmigosList.size() <= 0 )
		{
			empty_view.setVisibility(View.VISIBLE);
		}
	

	}

	private class AcceptRequestTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {

			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... arg0) {

			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("requestedBy", ID_by));
			params.add(new BasicNameValuePair("requestedTo", JsonFileUtility
					.ReadJsonData(Constants.TAG_UserGUID)));
			params.add(new BasicNameValuePair("response", "" + 1));
			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url_addfriend,
					ServiceHandler.POST, params);
			Log.d("Response: ", "> " + jsonStr);
			if (jsonStr != null) {
				JSONObject jsonobj;
				try {
					jsonobj = new JSONObject(jsonStr);
					Boolean Success_add = jsonobj.getBoolean("success");
					Log.d("tag", "" + Success_add);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);

			swipeView.setRefreshing(true);
			new FetchAmigosTask().execute();

		}

	}


	private class RejectRequesttask extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {

			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... arg0) {

			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("requestedBy", ID_by));
			params.add(new BasicNameValuePair("requestedTo", JsonFileUtility
					.ReadJsonData(Constants.TAG_UserGUID)));
			params.add(new BasicNameValuePair("response", "" + 3));
			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url_addfriend,
					ServiceHandler.POST, params);
			Log.d("Response: ", "> " + jsonStr);
			if (jsonStr != null) {
				JSONObject jsonobj;
				try {
					jsonobj = new JSONObject(jsonStr);
					Boolean Success_add = jsonobj.getBoolean("success");
					Log.d("tag", "" + Success_add);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);

			swipeView.setRefreshing(true);
			new FetchAmigosTask().execute();

		}

	}

	@Override
	public void onBackPressed() {

	}

}
